package com.adcc.ags.agent.healthcheck;

import com.adcc.utility.log.Log;
import com.codahale.metrics.health.HealthCheck;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;

import java.util.*;

/**
 * 网络健康检查
 */
public class NetworkHealthCheck extends HealthCheck{

    // 网卡名称
    private String networkDevice;

    // 网络RX流量数组
    private List<Long> rxList = Collections.synchronizedList(new ArrayList<Long>());

    // 网络TX流量数组
    private List<Long> txList = Collections.synchronizedList(new ArrayList<Long>());

    /**
     * 构造函数
     */
    public NetworkHealthCheck(String networkDevice){
        this.networkDevice = networkDevice;

        // 初始化网络RX流量数组
        rxList.add(0L);
        rxList.add(0L);
        rxList.add(0L);
        rxList.add(0L);
        rxList.add(0L);

        // 初始化网络TX流量数组
        txList.add(0L);
        txList.add(0L);
        txList.add(0L);
        txList.add(0L);
        txList.add(0L);
    }

    @Override
    protected Result check() {
        Sigar sigar = null;
        try {
            sigar = new Sigar();
            NetInterfaceStat stat = sigar.getNetInterfaceStat(networkDevice);
            long lRx = stat.getRxBytes();
            rxList.remove(0);
            rxList.add(lRx);
            long lTx = stat.getTxBytes();
            txList.remove(0);
            txList.add(lTx);
            Map<String,List<Long>> map = Maps.newHashMapWithExpectedSize(2);
            map.put("rx",rxList);
            map.put("tx",txList);
            return Result.healthy(new ObjectMapper().writeValueAsString(map));
        }catch (Exception ex){
            Log.error(NetworkHealthCheck.class.getName(),"check() error",ex);
            return Result.unhealthy(ex.fillInStackTrace());
        }finally {
            if(sigar != null){
                sigar.close();
            }
        }
    }
}
